package com.htthorizon.model.service;

import java.util.*;

import cn.hutool.core.date.DateTime;
import com.github.pagehelper.Page;
import com.github.yitter.idgen.YitIdHelper;
import com.htthorizon.common.core.constant.Constants;
import com.htthorizon.common.core.domain.R;
import com.htthorizon.common.core.exception.ServiceException;
import com.htthorizon.common.core.utils.DateUtils;
import com.htthorizon.common.core.utils.StringUtils;
import com.htthorizon.common.core.web.page.TableDataInfo;
import com.htthorizon.common.security.utils.DictUtils;
import com.htthorizon.common.security.utils.SecurityUtils;
import com.htthorizon.model.domain.ModelSource;
import com.htthorizon.model.mapper.SysUserModelMapper;
import com.htthorizon.model.response.ModelMessageVo;
import com.htthorizon.model.response.ModelUseDto;
import com.htthorizon.system.api.RemoteModelService;
import com.htthorizon.system.api.domain.SysUser;
import com.htthorizon.system.api.model.LoginUser;
import com.htthorizon.system.api.model.ModelInfoReq;
import com.htthorizon.model.response.ModelSpecialityDto;
import com.htthorizon.system.api.domain.SysDictData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.htthorizon.model.mapper.ModelInfoMapper;
import com.htthorizon.model.domain.ModelInfo;
import org.springframework.util.CollectionUtils;

/**
 * 模型信息Service业务层处理
 *
 * @author ht
 * @date 2023-11-15
 */
@Service
@Slf4j
public class ModelInfoServiceImpl implements IModelInfoService
{
    @Autowired
    private ModelInfoMapper modelInfoMapper;

    @Autowired
    private SysUserModelMapper sysUserModelMapper;

    @Autowired
    private RemoteModelService remoteModelService;

    @Autowired
    private IModelUseService modelUseService;
    
    @Autowired
    private IModelSourceService modelSourceService;

    /**
     * 查询模型信息
     *
     * @param id 模型信息主键
     * @return 模型信息
     */
    @Override
    public ModelInfo selectModelInfoById(Long id)
    {
        return modelInfoMapper.selectModelInfoById(id);
    }

    /**
     *  按专业域分组统计
     * @param modelInfo
     * @return
     */
    @Override
    public List<ModelSpecialityDto> selectModelInfoGroupBySpeciality(ModelInfo modelInfo){
        List<SysDictData> dictList = DictUtils.getDictCache(Constants.DICT_SPECIALITY_CODE);
        if(dictList != null && dictList.size() > 0) {
            List<ModelSpecialityDto> modelSpecialityDtoList = new ArrayList<>(dictList.size());
            List<ModelSpecialityDto> dtoList = modelInfoMapper.selectModelInfoGroupBySpeciality(modelInfo);
            Map<String, Integer> modelSpecialityMap = null;
            if(dtoList != null && dtoList.size() > 0) {
                modelSpecialityMap = new HashMap<>(dtoList.size());
                for (ModelSpecialityDto modelSpecialityDto : dtoList) {
                    modelSpecialityMap.put(modelSpecialityDto.getSpecialityCode(), modelSpecialityDto.getCnt());
                }
            }
            for (SysDictData dictData:dictList) {
                ModelSpecialityDto modelSpecialityDto = new ModelSpecialityDto();
                modelSpecialityDto.setSpecialityName(dictData.getDictLabel());
                modelSpecialityDto.setSpecialityCode(dictData.getDictValue());
                //该专业域下没有模型的，数量设置为0
                if(!CollectionUtils.isEmpty(modelSpecialityMap) && modelSpecialityMap.get(dictData.getDictValue())!=null) {
                    modelSpecialityDto.setCnt(modelSpecialityMap.get(dictData.getDictValue()));
                }else{
                    modelSpecialityDto.setCnt(0);
                }
                modelSpecialityDtoList.add(modelSpecialityDto);
            }
            return modelSpecialityDtoList;
        }
        return null;
    }

    /**
     * 查询模型信息列表
     *
     * @param modelInfo 模型信息
     * @return 模型信息
     */
    @Override
    public List<ModelInfo> selectModelInfoList(ModelInfo modelInfo)
    {

        List<ModelInfo> modelList = modelInfoMapper.selectModelInfoList(modelInfo);

        if(!SecurityUtils.isAdmin(SecurityUtils.getUserId()) && !CollectionUtils.isEmpty(modelList)){
            //查询该用户可编辑的模型列表
            Map<Long,Map<String,Long>> modelMap = this.sysUserModelMapper.selectModelListByUserId(SecurityUtils.getUserId());
            for (ModelInfo model:modelList){
                if(modelMap.get(model.getId()) == null || modelMap.get(model.getId()).size() == 0){
                    model.setIsModify(1);
                }
            }
        }
        return modelList;
    }

    @Override
    public TableDataInfo selectModelInfoList2(ModelInfo modelInfo, Page<ModelMessageVo> pages, TableDataInfo tableDataInfo) {
      Integer total=  modelInfoMapper.count(modelInfo);
        List<ModelInfo> modelList = modelInfoMapper.getPage((pages.getPageNum()-1)*pages.getPageSize(),pages.getPageSize(),modelInfo);
        for (ModelInfo modelInfo1:modelList){
            List<ModelUseDto> modelUse = modelUseService.getModelUse(Integer.valueOf(modelInfo1.getSpecialityCode()), 1, 500);
            for (ModelUseDto modelUseDto:modelUse){
                if (modelUseDto.getModelName().equals(modelInfo1.getModelName())){
                    modelInfo1.setModelUseCount(Integer.valueOf(modelUseDto.getUsefreq()));
                }
            }
        }

        if(!SecurityUtils.isAdmin(SecurityUtils.getUserId()) && !CollectionUtils.isEmpty(modelList)){
            //查询该用户可编辑的模型列表
            Map<Long,Map<String,Long>> modelMap = this.sysUserModelMapper.selectModelListByUserId(SecurityUtils.getUserId());
            for (ModelInfo model:modelList){
                if(modelMap.get(model.getId()) == null || modelMap.get(model.getId()).size() == 0){
                    model.setIsModify(1);
                }
            }
        }
        try{
            for (ModelInfo o:modelList){
                ModelSource modelSource = modelSourceService.selectModelSourceById(o.getSourceId());
                o.setSourceName(modelSource.getSourceName());
            }
        }catch (Exception e){
            e.printStackTrace();
        }


        tableDataInfo.setTotal(total);
        tableDataInfo.setRows(modelList);
        return  tableDataInfo;
    }


    /**
     * 新增模型信息
     *
     * @param modelInfoReq 模型信息
     * @return 结果
     */
    @Override
    public int insertModelInfo(ModelInfoReq modelInfoReq)
    {
        ModelInfo modelInfo = new ModelInfo();
        if (modelInfoReq.getModelNameEn().equals("")){
            modelInfoReq.setModelNameEn(null);
        }
        BeanUtils.copyProperties(modelInfoReq, modelInfo);
        modelInfo.setCreateTime(DateUtils.getNowDate());
        modelInfo.setStatus(Constants.DELETE_STATUS_NO);
        modelInfo.setCreateBy(SecurityUtils.getUsername());
        modelInfo.setModelUseCount(0);
        //生成code
        long newId = YitIdHelper.nextId();
        modelInfo.setModelCode(String.valueOf(newId));
        int count = modelInfoMapper.insertModelInfo(modelInfo);
        modelInfoReq.setId(modelInfo.getId());
        //保存元数据
        if (!Objects.isNull(modelInfo.getSourceId())){
            R<Boolean>  r = remoteModelService.saveMeta(modelInfoReq);
            if(r.getCode() == R.FAIL){
                count=0;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        String roleKey="107";
        if((!roleKey.equals("107"))&&(!roleKey.equals("105"))){
            //查询该用户可编辑的模型列表
            System.out.println(111111);
                throw new ServiceException("该用户没有编辑此模型的权限！");
        }
    }
    /**
     * 修改模型信息
     *
     * @param modelInfoReq 模型信息
     * @return 结果
     */
    @Override
    public int updateModelInfo(ModelInfoReq modelInfoReq)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        String roleKey = sysUser.getRoles().get(0).getRoleKey();
        log.info("roleKey : {}" , roleKey);
        if((!roleKey.equals("107"))&&(!roleKey.equals("105"))){
            //查询该用户可编辑的模型列表
            log.info("检验该用户是否具有模型权限");
            Map<Long,Map<String,Long>> modelMap = this.sysUserModelMapper.selectModelListByUserId(SecurityUtils.getUserId());
            if(modelMap.get(modelInfoReq.getId()) == null || modelMap.get(modelInfoReq.getId()).size() == 0){
                throw new ServiceException("该用户没有编辑此模型的权限！");
            }
        }
        ModelInfo modelInfo = new ModelInfo();
        BeanUtils.copyProperties(modelInfoReq, modelInfo);
        modelInfo.setUpdateBy(SecurityUtils.getUsername());
        modelInfo.setUpdateTime(DateUtils.getNowDate());
        int count = modelInfoMapper.updateModelInfo(modelInfo);
        //保存元数据
        if (!Objects.isNull(modelInfo.getSourceId())){
            R<Boolean>  r = remoteModelService.saveMeta(modelInfoReq);
            if(r.getCode() == R.FAIL){
                count=0;
            }
        }
        return count;
    }

    /**
     * 更改模型使用次数
     * @param id
     * @return
     */
    @Override
    public int updateModelInfoUseCount(Long id){
        return this.modelInfoMapper.updateModelInfoUseCount(id);
    }

    /**
     * 批量删除模型信息
     *
     * @param ids 需要删除的模型信息主键
     * @return 结果
     */
    @Override
    public int deleteModelInfoByIds(Long[] ids)
    {
        return modelInfoMapper.deleteModelInfoByIds(ids);
    }

    /**
     * 删除模型信息信息
     *
     * @param id 模型信息主键
     * @return 结果
     */
    @Override
    public int deleteModelInfoById(Long id)
    {
        return modelInfoMapper.deleteModelInfoById(id);
    }

    @Override
    public List<ModelInfo> list() {
        return modelInfoMapper.list();
    }

    @Override
    public List<ModelInfo> queryTimeLimit(DateTime date, DateTime lastMonth) {
        return modelInfoMapper.selectTimeLimit(date,lastMonth);
    }

    @Override
    public boolean checkModelInfo(ModelInfoReq modelInfo) {
        return   modelInfoMapper.countModelInfoByModelName(modelInfo.getModelName())==0;
    }


}
